class Node {
    constructor (element, next) {
        this.element = element
        this.next = next
    }
}

class LinkedList {
    constructor(head, size) {
        this.head = null
        this.size = 0
    }
    _getNode(index) {
        if(index<0 || index>= this.size) {
            throw new Error('越界了')
        }
        let currentNode = this.head
        for(let i=0;i<index;i++) {
            currentNode = currentNode.next
        }
        return currentNode
    }
    add (index, element) {
        if(arguments.length === 1) {
            element = index
            index = this.size
        }
        // 判断插入的位置是否合理
        if(index < 0 || index > this.size) {
            throw new Error('cross the border')
        }
        if(index === 0) {
            let head = this.head
            this.head = new Node(element, head)
        } else {
            let prevNode = this._getNode(index-1)
            prevNode.next = new Node(element, prevNode.next)
        }
        this.size ++
    }
    remove(index) {
        let rmNode = null
        if(index === 0) {
            rmNode = this.head
            if(!rmNode) {
                return undefined
            }
            this.head = rmNode.next
        } else {
            let prevNode = this._getNode(index-1)
            rmNode = prevNode.next
            prevNode.next = prevNode.next.next
        }
        this.size --
        return rmNode
    }
    set (index, element) {
        let node = this._getNode(index)
        node.element = element
    }
    get (index) {
        return this._getNode(index)
    }
    clear () {
        this.head = null
        this.size = 0
    }
}








const l1 = new LinkedList()
console.log(l1)
// 默认空链表  -> LinkedList { head: null, size: 0 }
// 添加了一项  -> LinkedList { head: Node { element: 'node1', next: null }, size: 1 }
l1.add('node1')
l1.add('node2')
l1.add(1,'node3')
l1.remove(1)
console.log(l1)
// l1.remove(1)
l1.set(1,'node3-3')
console.log(l1)



// 队列： 先进先出
class Queue {
    constructor () {
        this.LinkedList = new LinkedList()
    }
    adQueue(data) {
        this.LinkedList.add(data)
    }
    deQueue() {
        return this.LinkedList.remove(0)
    }
}

const q = new Queue()

q.adQueue('node1')
q.adQueue('node2')

q.deQueue()
let a = q.deQueue()
console.log(a)